import 'package:enjoy_plus_three/stores/counter.dart';
import 'package:enjoy_plus_three/utils/event_bus.dart';
import 'package:enjoy_plus_three/utils/http.dart';
import 'package:enjoy_plus_three/utils/logger.dart';
import 'package:enjoy_plus_three/utils/toast.dart';
import 'package:enjoy_plus_three/utils/token.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});

  int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  @override
  void initState() {
    // 订阅 登录页 发布的重新获取用户信息的事件
    eventBus.on<RefreshMine>().listen((event) {
      _getProfile();
    });
    super.initState();
  }

  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  // 用户信息
  Map userInfo = {'id': '', 'avatar': null, 'nickName': null};

  _getProfile() async {
    final res = await http.get('/userInfo');
    if (res['code'] != 10000) return ToastUtil.showError('用户信息获取失败');
    setState(() {
      userInfo = res['data'];
    });
  }

  // 页面重构时就会触发回调的钩子 - 组件重构时触发
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    // 通过 widget.变量名 获取父组件的变量数据

    if (widget.currentIndex == 1) {
      // logger.i('-----页面重构加载了${widget.currentIndex}');
      //  发送请求 - 获取用户资料
      // 获取用户资料
      _getProfile();
    }
    super.didUpdateWidget(oldWidget);
  }

  // 测试token - 获取房屋
  _getHouse() async {
    final res = await http.get('/house');
    logger.i(res);
  }

  @override
  Widget build(BuildContext context) {
    // 获取 Counter 模型
    final counter = Provider.of<Counter>(context);
    return Scaffold(
        backgroundColor: const Color.fromARGB(200, 85, 145, 175),
        appBar: AppBar(
          title:
              Text('我的${counter.count}', style: TextStyle(color: Colors.white)),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: ListView(
          children: [
            // 个人信息
            Container(
                padding: const EdgeInsets.all(10),
                child: GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/profile',
                          arguments: userInfo);
                    },
                    child: Row(children: [
                      Row(children: [
                        ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child: userInfo['avatar'] != null
                                ? Image.network(userInfo['avatar'],
                                    width: 50, height: 50)
                                : Image.asset('assets/images/avatar_1.jpg',
                                    width: 50, height: 50)),
                        const SizedBox(width: 10),
                        Text(userInfo['nickName'] ?? '用户名',
                            style: const TextStyle(
                                fontSize: 16, color: Colors.white))
                      ]),
                      const Spacer(),
                      const Row(children: [
                        Text(
                          '去完善信息',
                          style: TextStyle(color: Colors.white),
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.white,
                          size: 13,
                        )
                      ])
                    ]))),
            Container(
                padding: const EdgeInsets.all(15),
                margin: const EdgeInsets.only(
                    top: 20, left: 10, right: 10, bottom: 20),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: Column(
                    children: menuList.map((item) {
                  return SizedBox(
                      height: 50,
                      child: Row(children: [
                        Row(
                          children: [
                            Image.asset(
                              item['icon'],
                              width: 20,
                              height: 20,
                            ),
                            const SizedBox(
                              width: 10,
                            ),
                            Text(
                              item['title'],
                              style: const TextStyle(fontSize: 16),
                            )
                          ],
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.arrow_forward_ios,
                          size: 12,
                          color: Colors.grey,
                        )
                      ]));
                }).toList())),
            ElevatedButton(
                onPressed: () {
                  _getHouse();
                },
                child: const Text('测试token失效')),

            ElevatedButton(
                onPressed: () {
                  counter.increment();
                },
                child: const Text('点我+1')),
          ],
        ));
  }
}
